<?php

namespace app\api\controller;
//导入基类

use app\common\model\FightTeam;
use app\common\model\Message;
use app\common\model\Reward;
use app\common\model\Sendmsg;
use app\common\model\User;
use app\common\model\Money as moneyModel;
use app\common\model\UserCoupon;
use app\common\validate\Goods;
use app\common\model\Goods as goodsModel;
use app\langjinmobile\model\Money;
use think\Controller;
use think\facade\Cache;
use think\Db;
use app\common\model\Shoporder;
use think\Request;
use Endroid\QrCode\QrCode;
use app\common\model\WalletLog;
class Login extends Controller
{
    public function index(){
        $code = $_REQUEST['code'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx128c7a418bf79c7e&secret=685f2146c6e1945906fd7c78c3020578&code='.$code.'&grant_type=authorization_code';
        header("location:".$url);
    }
    public  function getAccessToken()
    {
        $code = empty($_REQUEST['code'])?'':$_REQUEST['code'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx128c7a418bf79c7e&secret=685f2146c6e1945906fd7c78c3020578&code='.$code.'&grant_type=authorization_code';
        $result =  file_get_contents($url);
        $result_arr = json_decode($result,true);
        $token = $result_arr['access_token'];
        $refresh = $result_arr['refresh_token'];
        $openid = $result_arr['openid'];
        if($openid){
            $list = User::where('openid',$openid)->find();
            if($list){
                session('parent_id',null);
                //如果用户已存在，直接登陆
                session('userid', $list['id']);
                session('openid', $list['openid']);
                //print_r($_SESSION);exit;
                header("location:".$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/mobile/travel/html/index.html');
            }else{
                $parent_id = empty(session('parent_id'))?'':session('parent_id');
                //如果不存在，添加user用户表
                $url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
                $result1 =  file_get_contents($url1);
                $result_arr1 = json_decode($result1,true);
                $user_info = [
                    'head_img' => $result_arr1['headimgurl'],
                    'nickname' => $result_arr1['nickname'],
                    'openid' => $result_arr1['openid'],
                    'sex' => $result_arr1['sex'],
                    'parent_id' => $parent_id,
                    'create_time' => time(),
                    'update_time' => time(),
                    'user_level' =>0,
                ];
                $uid= User::insertGetId($user_info);//user表
                if($uid){
                    session('parent_id',null);
                    //3注册money表
                    $money['userid'] = $uid;
                    $money['balance'] = '0';
                    $money['integral'] = '0';
                    $money['create_time'] = time();
                    moneyModel::insert($money);//money表添加数据
                    session('userid', $uid);
                    session('openid', $result_arr1['openid']);
                    //print_r($_SESSION);exit;
                }
                header("location:".$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/mobile/travel/html/index.html');
            }

        }
    }
    public function login(){
        $parent_id = empty($_REQUEST['parent_id'])?'':$_REQUEST['parent_id'];
        if($parent_id){
            $count = User::where('id',$parent_id)->count();
            if($count){
                session('parent_id',$parent_id);
            }
        }
            $tiaozhuan_url = urlencode($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/api/login/getAccessToken');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx128c7a418bf79c7e&redirect_uri='.$tiaozhuan_url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header("location:".$url);
    }
	public function peizhi()
    {
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $token = 'lvyou';
        $signature = $_GET['signature'];
        $array = array($timestamp, $nonce, $token);
//2.将排序后的三个参数拼接之后用sha1加密
        $tmpstr = implode('', $array);
        $tmpstr = sha1($tmpstr);
//3.将加密后的字符串与signature进行对比，判断该请求是否来自微信
        if ($tmpstr == $signature) {
            header('content-type:text');
            echo $_GET['echostr'];
            exit;
        }
    }
    public function response (){
        $data    = file_get_contents('php://input');
        $data = $this->xml_to_data($data);
        // sign不参与签名算法
        $data_sign = $data['sign'];
        unset($data['sign']);
        $sign = $this->makeSign($data);
        $str = '';
        /*foreach($data as $key=>$value){
            $str .= $key.':'.$value.'+++';
        }*/
        // 判断签名是否正确 判断支付状态
        if (($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
            //file_put_contents('6666.txt',$data['out_trade_no']);
            //改变订单状态
            $info  = Shoporder::where('order_number',$data['out_trade_no'])->find();
            $res = Shoporder::where('order_number',$data['out_trade_no'])->update(['status'=>1]);
            $user_info = User::where('id',$info['userid'])->field('nickname,mobile')->find();
            //如果使用优惠券的话更改优惠券状态
            if($info['coupon_id']){
                $result = UserCoupon::where(['id'=>$info['coupon_id'],'userid'=>$info['userid']])->update(['status'=>1]);
            }
            if($res){
                if($user_info['mobile']){
                    //发送短信
                    $this->sendmsg($user_info['nickname'],$data['out_trade_no'],$user_info['mobile']);
                }
                $parent_id = User::where('id',$info['userid'])->value('parent_id');
                //给上级返佣金
                $this->return_commission($parent_id,$info['tprice']);
                //如果是拼团订单的话判断该拼团团队是否可以改为拼团成功状态
                $this->action_fight_order($info['fight_id'],$info['goods__id']);
                return 'SUCCESS';
            }
        }else{
            return 'FALL';
        }
    }
    public function action_fight_order($fight_id,$goods_id){
        //如果是拼团订单的话判断该拼团团队是否可以改为拼团成功状态
        if($fight_id){
            $info  = FightTeam::where('id',$fight_id)->find();
            if($info['status'] == 0 && $info){
                $count = Shoporder::where('fight_id',$info['id'])->where('status',1)->count();
                $people_count = goodsModel::where('id',$goods_id)->value('people_count');
                if($count >= $people_count){
                    //如果满足就把该拼团结束
                    FightTeam::where('id',$fight_id)->update(['status'=>1]);
                }
            }else{
                Shoporder::where('fight_id',$info['id'])->where('status',1)->update(['status'=>5,'reason'=>'拼团超时']);
            }
        }
    }
    public function sendmsg($nickname,$order_number,$mobile)
    {
        $info = Sendmsg::where('id',1)->find();
//设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
        $result = $this->sendSMS($mobile, sprintf($info['tpl_name'],$nickname,$order_number),true,$info['appkey'],$info['appkey_name']);

        if (!is_null(json_decode($result))) {

            $output = json_decode($result, true);

            if (isset($output['code']) && $output['code'] == '0') {
                echo '发送成功';
            } else {
                echo $output['errorMsg'];
            }
        } else {
            echo $result;
        }
    }
    /**
     * 发送短信
     *
     * @param string $mobile 		手机号码
     * @param string $msg 			短信内容
     * @param string $needstatus 	是否需要状态报告
     */
    public function sendSMS( $mobile, $msg, $needstatus = 'true',$account,$password) {

        //创蓝接口参数
        $postArr = array (
            'account'  => $account,
            'password' => $password,
            'msg' => urlencode($msg),
            'phone' => $mobile,
            'report' => $needstatus
        );
        $result = $this->curlPost( 'http://smssh1.253.com/msg/send/json', $postArr);
        //var_dump($postArr);die();
        return $result;
    }
    /**
     * 通过CURL发送HTTP请求
     * @param string $url  //请求URL
     * @param array $postFields //请求参数
     * @return mixed
     *
     */
    private function curlPost($url,$postFields){
        $postFields = json_encode($postFields);

        $ch = curl_init ();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'   //json版本需要填写  Content-Type: application/json;
            )
        );
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt( $ch, CURLOPT_TIMEOUT,60);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec ( $ch );
        if (false == $ret) {
            $result = curl_error(  $ch);
        } else {
            $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 ". $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close ( $ch );
        return $result;
    }
    public function return_commission($userid,$money){
        //升级vip人数
        $people_number = Reward::where('field','invite_number')->value('tip');
        //邀请佣金比例
        $invite_scale = Reward::where('field','invitation_commissio')->value('value');
        //推广佣金
        $tuiguang_num = Reward::where('field','promotion_commission')->value('value');
        //父级的当前等级
        $user_level = User::where('id',$userid)->value('user_level');
        if($user_level){
            //如果是vip的话直接获得邀请佣金和推广佣金
            $data = [
                //添加积分记录
                'userid' => $userid,
                'money' => $money*$invite_scale/100,
                'type' => 4,//邀请佣金
            ];
            $data1 = [
                //添加积分记录
                'userid' => $userid,
                'money' => $tuiguang_num,
                'type' => 5,//邀请佣金
            ];
            $res = WalletLog::create($data);
            $res1 = WalletLog::create($data1);
            if($res && $res1){
                Money::where('userid',$userid)->setInc('balance',($money*$invite_scale/100)+$tuiguang_num);
            }
        }else{
            //父级当前邀请人数
            $child_num = User::where('parent_id',$userid)->count();
            if($child_num >=$people_number){
                //如果父级是普通会员 且符合升级标准，给父级升级为vip
                User::where('id',$userid)->update(['user_level'=>1]);
                $data = [
                    //添加积分记录
                    'userid' => $userid,
                    'num' => $money*$invite_scale/100,
                    'type' => 4,//邀请佣金
                ];
                $data1 = [
                    //添加积分记录
                    'userid' => $userid,
                    'money' => $tuiguang_num,
                    'type' => 5,//邀请佣金
                ];
                $res = WalletLog::create($data);
                $res1 = WalletLog::create($data1);
                if($res && $res1){
                    Money::where('userid',$userid)->setInc('balance',($money*$invite_scale/100)+$tuiguang_num);
                }
            }else{
                //如果不满足升级条件的话 就只获得邀请佣金
                $data = [
                    //添加积分记录
                    'userid' => $userid,
                    'num' => $money*$invite_scale/100,
                    'type' => 4,//邀请佣金
                ];
                $res = WalletLog::create($data);
                if($res){
                    Money::where('userid',$userid)->setInc('balance',($money*$invite_scale/100));
                }
            }
        }



    }
    public function xml_to_data($xml){
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
    /**
     * 接收通知成功后应答输出XML数据
     * @param string $xml
     */
    public function replyNotify(){
        $data['return_code'] = 'SUCCESS';
        $data['return_msg'] = 'OK';
        $xml = $this->data_to_xml( $data );
        echo $xml;
        die();
    }

    function data_to_xml($arr){
        $xml = "<root>";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$key.">".data_to_xml($val)."</".$key.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        $xml.="</root>";
        return $xml;
    }

    /**

     * 生成签名

     * @return 签名，本函数不覆盖sign成员变量

     */

    protected function makeSign($data){

        //获取微信支付秘钥

        //require_once "wxpay/lib/WxPay.Api.php";

        $key = '4C117F2037181C74559DB1829298E041';

        // 去空

        $data=array_filter($data);

        //签名步骤一：按字典序排序参数

        ksort($data);

        $string_a=http_build_query($data);

        $string_a=urldecode($string_a);

        //签名步骤二：在string后加入KEY

        //$config=$this->config;

        $string_sign_temp=$string_a."&key=".$key;

        //签名步骤三：MD5加密

        $sign = md5($string_sign_temp);

        // 签名步骤四：所有字符转为大写

        $result=strtoupper($sign);

        return $result;

    }
    //操作超时支付的订单
    public function timeout_order(){
        ini_set('memory_limit','512M');    // 临时设置最大内存占用为3G
        set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期
        $order_info = Shoporder::where('status',0)->select();
        foreach($order_info as &$value){
           $time = strtotime($value['create_time'])+300;
            //超过5分钟未支付的订单改变订单状态
            if($time<time()){
                Shoporder::where('order_id',$value['order_id'])->update(['status'=>4,'reason'=>'超时未支付']);
                goodsModel::where('id',$value['goods_id'])->setInc('amount',1);
            }
        }
       return 'success';
    }
    //操作拼团订单 如果拼团时间结束还未完成就改变拼团状态
    public function fight_team(){
        ini_set('memory_limit','512M');    // 临时设置最大内存占用为3G
        set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期
        //查出来所有正在拼团的数据
        $info = FightTeam::where('status',0)->select();
        foreach($info as &$value){
            if($value['expired_time'] <=time()){
                //如果时间到了
                $res = FightTeam::where('id',$value['id'])->update(['status'=>1]);
                if($res){
                    $count = Shoporder::where('fight_id',$value['id'])->where('status','in','0,1')->count();
                    $goods_id = Shoporder::where('fight_id',$value['id'])->value('goods_id');
                    $people_count = goodsModel::where('id',$goods_id)->value('people_count');
                    if($count <$people_count){
                        Shoporder::where('fight_id',$value['id'])->where('status',1)->update(['status'=>5,'reason'=>'拼团超时']);
                    }
                }
            }
        }
        return 'success';
    }
}